<?php
defined('EXEC') or die();
$transacao = 'estoque';

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}
//Importando a classes
Loader::import('com.atitudeweb.SQL');
Controller::addHead('fullcalendar', 'css');
Controller::addHead('fullcalendar.print', 'css');
Controller::addHead('jquery.blockUI', 'js');
Controller::addHead('globalize', 'js');
Controller::addHead('globalize.culture.pt-BR', 'js');
Controller::addHead('fullcalendar', 'js');
Controller::addHead('gcal', 'js');
$form 			= false;
$rowEdit 		= array();
$table 			= 'tethys.tb_estoque ';
$tableEdit      = 'tethys.tb_estoque es inner join tethys.tb_local_empresa le on es.cd_localempresa = le.ci_local inner join tethys.tb_itens ti on ti.ci_item =es.cd_item inner join tethys.tb_unidade_medida um on es.cd_unidade_estoque = um.ci_unidade_medida';
$tablepk 		= 'cd_item';
$limitPagina 	= 10; //Registros por página
$faixa 			= 10; //Faixa de páginas que irão ser mostradas paginação (google)
$dif 			= 5; //A diferença que a faixa de páginas irão começar a caminhar (google)
$p 				= (@$_GET['p'] ? $_GET['p'] : 1);
$id_update         = @$_POST['id_update'];
$id_insert         = @$_POST['id_insert'];

//Mudança do formulário para adição ou alteração de registro
if(isset($_GET['form'])){
	if($_GET['form'] == 0){
		$btFormLabel = 'Adicionar';
	}
	else{
		$btFormLabel = 'Salvar';
		$rowEdit =  query("select * from $table where $tablepk = ".$_GET['form'])->fetch();
	}
	$form = true;
}

//Consulta no banco e mecânica de paginação
if(isset($_POST['search1']) || !$form){
	@$where .= " where 1=1 ";
	if(isset($_POST['search1']) && (!empty($_POST['search1'])) ){
		$term = addslashes($_POST['search1']);
		if (!empty($term)){
			$where .=  " and cd_item ={$term}";}
	}

	if(isset($_POST['search6']) && (!empty($_POST['search6'])) ){
		$term = addslashes($_POST['search6']);
		if (!empty($term)){
			$where .=  " and ds_codigo like upper('%{$term}%') ";}
	}

	if(isset($_POST['search2']) && (!empty($_POST['search2'])) ){
		$term = addslashes($_POST['search2']);
		if (!empty($term)){
			$where .=  " and cd_categoria = {$term} ";}
	}
	if(isset($_POST['search3']) && (!empty($_POST['search3'])) ){
		$term = addslashes($_POST['search3']);
		if (!empty($term)){
			$where .=  " and cd_grupo= {$term} ";}
	}
	if(isset($_POST['search4']) && (!empty($_POST['search4'])) ){
		$term = addslashes($_POST['search4']);
		if (!empty($term)){
			$where .=  " and cd_classe= {$term} ";}
	}

	if(isset($_POST['search5']) && (!empty($_POST['search5'])) ){
		$term = addslashes($_POST['search5']);
		if (!empty($term)){
			$where .=  " and cd_localempresa= {$term} ";}
	}

	$sql=" select * from $tableEdit $where order by $tablepk asc limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
	$sqlc=" select count(*) as num from $tableEdit $where ";
	$query = query($sql);
	$rowNum = query($sqlc)->fetch();
	$registros = $rowNum['num'];
	$paginacao = Util::pagination($registros, 4);
}
?>
<h3>
	<i class="glyphicon glyphicon-user"></i> Estoque -
	<?php echo (!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?>
</h3>
<div class="panel panel-default">
	<div class="panel-body">
		<div id="alerts"></div>
		<?php if(!isset($_GET['form'])){ ?>
			<form action="<?php echo Util::setLink(array('p=null')); ?>"
				method="post" class="form">
				<div class="row" >
					<div class="col-md-12" >
						<div class="col-md-1">
							<div class="form-group">
								<label class="control-label">Id.:</label>
								<input type="text" name="search1" id="search1" 
								   style="width: 75px;" value="<?php echo @$_POST['search1']; ?>"
							       class="form-control" />       
							 </div>
						</div>
						<div class="col-md-1">	    
							<div class="form-group">   
								<label class="control-label">Código.:</label>
								<input type="text" name="search6" id="search6" style="width: 75px;"
									   value="<?php echo @$_POST['search6']; ?>"
							       		class="form-control" />
							</div>       		
						</div>	  
						<div class="col-md-10">
							<div class="form-group">
								<label class="control-label">Descrição.:</label>     						        
								<input type="text" name="ds_item" id="ds_item" style="width: 304px;"
									   value="<?php echo @$_POST['ds_item']; ?>"
									   class="form-control" />
							</div>
						</div>
					</div>
					<div class="col-md-12">
						<div class="col-md-1">
							<div class="form-group">
								<label class="control-label">CATEGORIA.:</label> 
								<select name="search2" id="search2" style="width: 384px;"
										class="form-control">
									<?php if($_GET['form'] == 0){
										$sql="select ci_categoria_item, ds_categoria_item from tethys.tb_categoria_item order by ds_categoria_item";
										echo '<option value="" >Selecione uma Categoria</option>';
										$rs = Connection::query($sql);
										while($row = $rs->fetch()){
											$select = $row["ci_categoria_item"] == $_POST['search2'] ? "selected" : "";
											echo "<option value=\"".@$row["ci_categoria_item"]."\" $select>".$row["ds_categoria_item"]."</option>";
										}
									}?>
								</select>
							</div>
						</div>	
					</div>
					<div class="col-md-12">
						<div class="col-md-1">
							<div class="form-group">
								<label class="control-label">GRUPO.:</label> 
								<select name="search3" id="search3" style="width: 384px;"class="form-control">
								<?php if($_GET['form'] == 0){
									$sql="select ci_grupo_item, ds_grupo_item from tethys.tb_grupo_item order by ds_grupo_item";
									echo '<option value="" >Selecione um Grupo</option>';
									$rs = Connection::query($sql);
									while($row = $rs->fetch()){
										$select = $row["ci_grupo_item"] == $_POST['search3'] ? "selected" : "";
										echo "<option value=\"".@$row["ci_grupo_item"]."\" $select>".$row["ds_grupo_item"]."</option>";
									}
								}?>
								</select>
							</div>
						</div>	
					</div>
					
					<div class="col-md-12">
						<div class="col-md-1">
							<div class="form-group">
								<label class="control-label">CLASSE.:</label>
								<select name="search4" id="search4" style="width: 384px;" class="form-control">
								<?php if($_GET['form'] == 0){
									$sql="select ci_classe_item, ds_classe_item from tethys.tb_classe_item order by ds_classe_item";
									echo '<option value="" >Selecione uma Classe</option>';
									$rs = Connection::query($sql);
									while($row = $rs->fetch()){
										$select = $row["ci_classe_item"] == $_POST['search4'] ? "selected" : "";
										echo "<option value=\"".@$row["ci_classe_item"]."\" $select>".$row["ds_classe_item"]."</option>";
									}
								}?>
								</select>
							</div>
						</div>	
					</div>
					<div class="col-md-12">
						<div class="col-md-1">
							<div class="form-group">
								<label class="control-label">ESTOQUE.:</label> 
								<select name="search5" id="search5" style="width: 384px;" class="form-control">
								<?php
								$sql=" select ci_local,ds_local from tethys.tb_local_empresa where fl_estoque='S' and fl_ativo='S'";
								echo '<option value="" >Selecione um Local de Estoque</option>';
								$rs = Connection::query($sql);
								while($row = $rs->fetch()){
									$select = $row["ci_local"] == $_POST['search5'] ? "selected" : "";
									echo "<option value=\"".@$row["ci_local"]."\" $select>".$row["ds_local"]."</option>";
								}
								?>
								</select>
							</div>
						</div>	
					</div>
					<div class="col-md-2">
						<div class="col-md-1">
							<div class="form-group">
								<button id="btSearch" class="btn btn-default btn-adjust">
									<span class="fa fa-search"></span>Consultar
								</button>
							</div>
						</div>	
					</div>
				</div>
			</form>
		<?php } ?>	
	<?php if(!isset($_GET['form'])){ ?>
		<!-- LISTAGEM DOS REGISTROS -->
		<form action="<?php echo Util::setLink(array('del='.$query->rowCount())) ?>" method="post" id="formSearch">
		<div class="table-responsive">
				<table
					class="table table-striped table-bordered table-hover table-condensed">
					<thead>
						<tr class="ui-widget-header">
							<th width="25" class="check"><input type="checkbox"
								id="btCheckAll" /></th>
							<th>Id.</th>
							<th>Cód.</th>
							<th>Descrição</th>
							<th>Rua</th>
							<th>Prateleira</th>
							<th>Escaninho</th>
							<th>Quantidade</th>
							<th>Unidade</th>
							<th>Custo</th>
						</tr>
					</thead>
			<tbody>
			<?php
			$count = 0;
			while($row = $query->fetch()){

				echo '<tr>
					    <td>'.$row['cd_item'].'</td>
						<td>'.$row['ds_codigo'].'</td>
						<td>'.$row['ds_item'].'</td>		                
		                <td>'.$row['rua'].'</td>
		                <td>'.$row['prateleira'].'</td>
		                <td>'.$row['escaninho'].'</td>
		                <td>'.$row['qdt']. '</td>
		                <td>'.$row['abv_unidade'].'</td>  
		                <td>'.'R$ '.str_replace('.',',',$row['custo_unit']).'</td>';  
				echo '</tr>';
				$count++;
			}
			?>
			</tbody>
		</table>
	</form>
	<div>
	<?php echo $paginacao; ?>
	<?php } ?>
	</div>
</div>
<style type="text/css">
.overlay {
	visibility: hidden;
	position: absolute;
	left: 20%;
	top: 30%;
	width: 55%;
	height: 38%;
	text-align: left;
	z-index: 1000;
	background-color: #CCC;
}

ul.none {
	list-style-type: none;
	display: inline;
}

#funcoes ul {
	padding: 0px;
	margin: 0px;
	float: left;
	width: 100%;
	background-color: #EDEDED;
	list-style: none;
}

#funcoes ul li {
	display: inline;
}

#funcoes ul li a {
	padding: 2px 10px;
	float: left;
	/* visual do link */
	background-color: #EDEDED;
	color: #333;
	text-decoration: none;
	border-bottom: 3px solid #EDEDED;
}

#funcoes ul li a:hover {
	background-color: #D6D6D6;
	color: #6D6D6D;
	border-bottom: 3px solid #EA0000;
}
</style>

	<script type="text/javascript">
function Seleciona_Radio(radio){
	document.getElementById("hdn_radio").value=radio;
}

$("#search1").change(function(){
		//alert($(this).val());
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });
	$.ajax({
			url: "partials/getItemById.php",
			type: "POST",
			data: { ci_item:$(this).val()},
			dataType: "json",
			success: function(json){
				//alert(json.logradouro);
				$("#loading").ajaxStop(function(){
				   $(this).hide();
				 });
				$('#search6').val(json.ds_codigo);
				$('#ds_item').val(json.ds_item);			
			}					
	});
});	

$("#search6").change(function(){
		//alert($(this).val());
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });
	$.ajax({
			url: "partials/getItemByCod.php",
			type: "POST",
			data: { param:$(this).val()},
			dataType: "json",
			success: function(json){
				//alert(json.logradouro);
				$("#loading").ajaxStop(function(){
				   $(this).hide();
				 });
				$('#search1').val(json.ci_item);			
				$('#ds_item').val(json.ds_item);			
			}					
	});
});	

</script>